﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace Lacrima.Framework.Infrastructure
{
    public class LinqToXmlAdapter
    {
        private string _basePath = @"..\Lacrima.Framework.Test\BookInfo.xml";  //XML文件路径   

        /// <summary>  
        /// 创建图书XML文档（创建）  
        /// </summary>  
        public void CreateXml<T>(List<T> bookList)
        {
            //创建XML文档  
            XDocument bookDoc = new XDocument();
            //创建声明对象  
            XDeclaration xDeclaration = new XDeclaration("1.0", "utf-8", "yes");
            bookDoc.Declaration = xDeclaration;    //指定XML声明对象  
            //创建bookstore节点  
            XElement xElement = new XElement(typeof(T).Name + "s");

            PropertyInfo[] properties = typeof(T).GetProperties();

            foreach (var book in bookList)
            {
                //创建book节点  
                XElement bookXml = new XElement(typeof(T).Name);

                foreach (var property in properties)
                {
                    //添加属性  
                    bookXml.Add(new XElement(property.Name, property.GetValue(book)));
                }
                //将book节点添加到bookstore节点中  
                xElement.Add(bookXml);
            }
            //保存文件  
            bookDoc.Add(xElement);
            bookDoc.Save(_basePath);
        }

        /// <summary>  
        /// 创建图书XML文档（创建）  
        /// </summary>  
        public void CreateBookXml()
        {
            //获取图书列表  
            List<BookInfo> bookList = GetBookList();
            //创建XML文档  
            XDocument bookDoc = new XDocument();
            //创建声明对象  
            XDeclaration xDeclaration = new XDeclaration("1.0", "utf-8", "yes");
            bookDoc.Declaration = xDeclaration;    //指定XML声明对象  
            //创建bookstore节点  
            XElement xElement = new XElement("bookstore");
            foreach (BookInfo book in bookList)
            {
                //创建book节点  
                XElement bookXml = new XElement("book");
                //添加属性  
                bookXml.Add(new XAttribute("id", book.BookId));
                bookXml.Add(new XAttribute("category", book.Category));
                //添加子节点  
                bookXml.Add(new XElement("title", book.Title));
                bookXml.Add(new XElement("author", book.Author));
                bookXml.Add(new XElement("publishDate", book.PublishDate.ToString("yyyy-MM-dd")));
                bookXml.Add(new XElement("price", book.Price));
                //将book节点添加到bookstore节点中  
                xElement.Add(bookXml);
            }
            //保存文件  
            bookDoc.Add(xElement);
            bookDoc.Save(_basePath);
        }

        /// <summary>    
        /// 获取图书列表(查询)    
        /// </summary>    
        /// <param name="param">参数条件</param>    
        /// <returns>图书列表</returns>   
        public List<BookInfo> GetBookInfoList(BookInfo param)
        {
            List<BookInfo> bookList = new List<BookInfo>();
            XElement xml = XElement.Load(_basePath);

            var bookVar = xml.Descendants("book");   //默认查询所有图书  
            if (param.BookId != 0) //根据图书ID查询    
            {
                bookVar = xml.Descendants("book").Where(a => a.Attribute("id").Value == param.BookId.ToString());
            }
            else if (!String.IsNullOrEmpty(param.Category)) //根据图书类别查询    
            {
                bookVar = xml.Descendants("book").Where(a => a.Attribute("category").Value == param.Category);
            }
            else if (!String.IsNullOrEmpty(param.Title)) //根据图书名称查询    
            {
                bookVar = xml.Descendants("book").Where(a => a.Element("title").Value == param.Title);
            }

            bookList = (from book in bookVar
                        select new BookInfo
                        {
                            BookId = int.Parse(book.Attribute("id").Value),
                            Category = book.Attribute("category").Value,
                            Title = book.Element("title").Value,
                            Author = book.Element("author").Value,
                            PublishDate = DateTime.Parse(book.Element("publishDate").Value),
                            Price = double.Parse(book.Element("price").Value)
                        }).ToList();
            return bookList;
        }

        /// <summary>    
        /// 增加图书信息（新增）    
        /// </summary>    
        /// <param name="param"></param>    
        /// <returns></returns>    
        public bool AddBookInfo(BookInfo param)
        {
            XElement xml = XElement.Load(_basePath);
            //创建book节点  
            XElement bookXml = new XElement("book");
            //添加属性  
            bookXml.Add(new XAttribute("id", param.BookId));
            bookXml.Add(new XAttribute("category", param.Category));
            //添加子节点  
            bookXml.Add(new XElement("title", param.Title));
            bookXml.Add(new XElement("author", param.Author));
            bookXml.Add(new XElement("publishDate", param.PublishDate.ToString("yyyy-MM-dd")));
            bookXml.Add(new XElement("price", param.Price));
            xml.Add(bookXml);
            //保存  
            xml.Save(_basePath);
            return true;
        }

        /// <summary>    
        /// 修改图书信息（修改）    
        /// </summary>    
        /// <param name="param"></param>    
        /// <returns></returns>    
        public bool EditBookInfo(BookInfo param)
        {
            bool result = false;
            if (param.BookId > 0)
            {
                //根据BookId找到要修改的图书XML  
                XElement xml = XElement.Load(_basePath);
                XElement bookXml = (from db in xml.Descendants("book") where db.Attribute("id").Value == param.BookId.ToString() select db).Single();
                //修改属性  
                bookXml.SetAttributeValue("category", param.Category);
                //修改子节点  
                bookXml.SetElementValue("title", param.Title);
                bookXml.SetElementValue("author", param.Author);
                bookXml.SetElementValue("publishDate", param.PublishDate.ToString("yyyy-MM-dd"));
                bookXml.SetElementValue("price", param.Price);
                //保存  
                xml.Save(_basePath);
                result = true;
            }
            return result;
        }

        /// <summary>    
        /// 删除图书信息（删除）    
        /// </summary>    
        /// <param name="param"></param>    
        /// <returns></returns>    
        public bool DeleteBookInfo(BookInfo param)
        {
            bool result = false;
            if (param.BookId > 0)
            {
                //根据BookId找到要删除的图书XML  
                XElement xml = XElement.Load(_basePath);
                XElement bookXml = (from db in xml.Descendants("book") where db.Attribute("id").Value == param.BookId.ToString() select db).Single();
                bookXml.Remove();
                //保存  
                xml.Save(_basePath);
                result = true;
            }
            return result;
        }

        /// <summary>  
        /// 获取图书列表  
        /// </summary>  
        /// <returns></returns>  
        public List<BookInfo> GetBookList()
        {
            List<BookInfo> bookList = new List<BookInfo>();
            //创建图书1  
            BookInfo book1 = new BookInfo()
            {
                BookId = 1,
                Category = "CHILDREN",
                Title = "Harry Potter",
                Author = "J K. Rowling",
                PublishDate = new DateTime(2005, 08, 15),
                Price = 29.99
            };
            bookList.Add(book1);
            //创建图书2  
            BookInfo book2 = new BookInfo()
            {
                BookId = 2,
                Category = "WEB",
                Title = "Learning XML",
                Author = "Erik T. Ray",
                PublishDate = new DateTime(2003, 10, 18),
                Price = 39.95
            };
            bookList.Add(book2);
            //创建图书3  
            BookInfo book3 = new BookInfo()
            {
                BookId = 3,
                Category = "WEB",
                Title = "XQuery Kick Start",
                Author = "James McGovern",
                PublishDate = new DateTime(2005, 6, 25),
                Price = 49.99
            };
            bookList.Add(book3);
            return bookList;
        }
    }  
}
